package helper;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.kxml.Xml;
import org.kxml.kdom.Document;
import org.kxml.kdom.Element;
import org.kxml.parser.XmlParser;

public class KXmlParser
{
	private XmlParser parser;
	private InputStream is;
	private Document doc;
	
	public KXmlParser()
	{
		
	}
	
	public void parseXml(String xml)
	{
		this.is = new ByteArrayInputStream(xml.getBytes());
		
		try
		{
			this.parser = new XmlParser(new InputStreamReader(this.is));
			this.doc = new Document();
			this.doc.parse(this.parser);
		} 
		catch (IOException e){ e.printStackTrace(); }
	}
	
	public int getStatusCode()
	{
		if(this.doc.getRootElement().getChild(0).equals(""))
			return -1;
			
		Element response = (Element) this.doc.getRootElement().getChild(0);
		int children = response.getChildCount();
		
		for(int i = 0 ; i < children ; i++)
		{
			if(response.getType(i) == Xml.ELEMENT)
			{
				Element current = response.getElement(i);
				if(current.getName().equalsIgnoreCase("status"))
				{
					for(int j = 0; j < current.getChildCount(); j++)
					{
						if(current.getElement(j).getName().equalsIgnoreCase("code"))
							return Integer.parseInt(current.getElement(j).getText());
					}
				}
			}
		}
		
		return -1;
	}

	public String getCoordinates()
	{

		if(this.doc.getRootElement().getChild(0).equals(""))
			return null;
		
		Element root = (Element) this.doc.getRootElement();
		
		if(root.getChildCount() < 1 || !((Element) root.getChild(0)).getName().equalsIgnoreCase("response"))
				System.out.println("O xml não corresponde ao formato esperado.");
		
		Element response = (Element) root.getChild(0);
				
		int children = response.getChildCount();
		
		for(int i = 0 ; i < children ; i++)
		{
			if(response.getType(i) == Xml.ELEMENT)
			{
				Element current = response.getElement(i);
				if(current.getName().equalsIgnoreCase("placemark"))
				{
					for(int j = 0; j < current.getChildCount(); j++)
					{
						if( (current.getType(j) == Xml.ELEMENT) && current.getElement(j).getName().equalsIgnoreCase("point"))
						{
							Element point = current.getElement(j);
							
							for(int k = 0; k < point.getChildCount() ; k++)
							{
								if(point.getElement(k).getName().equalsIgnoreCase("coordinates"))
									return point.getElement(k).getText();
							}
							
							break;
						}
					}
					
					break;
				}
			}
		}
		
		return null;
	}
}
